import React, { useState, useEffect, useRef } from 'react';
import {
  View,
  Text, StyleSheet, ActivityIndicator, Image, TouchableOpacity,
  Platform,
  Alert,
  Button
} from 'react-native';
import * as FileSystem from 'expo-file-system';
import * as ScreenOrientation from 'expo-screen-orientation';
import { shareAsync } from 'expo-sharing';
import { useEvent } from 'expo';
import { useVideoPlayer, VideoView } from 'expo-video';

const VideoPlayer = () => {
  const [loading, setLoading] = useState(true);
  const [cachedVideo, setCachedVideo] = useState(null);
  const [currentTime, setCurrentTime] = useState(0);
  const [totalDuration, setTotalDuration] = useState(0);
  const [isFullScreen, setIsFullScreen] = useState(false);
  const [error, setError] = useState(null);
  const videoSource = "https://media.w3.org/2010/05/sintel/trailer.mp4"

  const videoRef = useRef(null);

  const player = useVideoPlayer(videoSource, player => {
    player.loop = true;
    player.play();
  });

  const { isPlaying } = useEvent(player, 'playingChange', { isPlaying: player.playing });

  const xia1 = async () => {
    // 锁定屏幕为横屏模式
    await ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.LANDSCAPE);

    // 更新状态，设置当前为横屏模式
    setIsFullScreen(true);
  }


  // 下载视频
  const xia = async () => {
    const filename = 'small.mp4';
    const result = await FileSystem.downloadAsync(
      videoSource,
      FileSystem.documentDirectory + filename
    );
    save(result.uri, filename, 'video/mp4');
  }
  const save = async (uri: string, filename: string, mimeType: string) => {
    try {
      if (Platform.OS === 'android') {
        const permissions = await FileSystem.StorageAccessFramework.requestDirectoryPermissionsAsync()
        if (permissions.granted) {
          const base64 = await FileSystem.readAsStringAsync(uri, {
            encoding: FileSystem.EncodingType.Base64,
          });
          // 创建文件并写入
          const newUri = await FileSystem.StorageAccessFramework.createFileAsync(
            permissions.directoryUri,
            filename,
            mimeType
          );
          await FileSystem.writeAsStringAsync(newUri, base64, {
            encoding: FileSystem.EncodingType.Base64,
          });
          Alert.alert("文件已保存", `文件已成功保存到: ${newUri}`);
        } else {
          shareAsync(uri); // 如果没有权限，可以让用户分享文件
        }
      } else {
        shareAsync(uri)
      }
    } catch (error) {
      console.error("保存文件时出错:", error);
      Alert.alert("错误", "文件保存失败");
    }

  }


  return (
    <View style={[styles.container, isFullScreen && styles.fullScreen]}>
      <VideoView style={styles.video} player={player} allowsFullscreen
        allowsPictureInPicture
      />
      <View style={styles.controlsContainer}>
        <Button
          title={isPlaying ? 'Pause' : 'Play'}
          onPress={() => {
            if (isPlaying) {
              player.pause();
            } else {
              player.play();
            }
          }}
        />

      </View>
      <TouchableOpacity
        onPress={xia}
        style={styles.xia}
      >
        <Image
          source={require("../../assets/images/xiazaibai.png")}
          style={{
            width: 20,
            height: 20,
            marginTop: 40,
          }}
        ></Image>
      </TouchableOpacity>
      <TouchableOpacity
        onPress={xia1}
        style={styles.xia1}
      >
        <Image
          source={require("../../assets/images/横屏.png")}
          style={{
            width: 20,
            height: 20,
            marginTop: 40,
          }}
        ></Image>
      </TouchableOpacity>

    </View>
  );
};


const styles = StyleSheet.create({
  fullScreen: {
    flexDirection: 'row', // 横向排列
    justifyContent: 'center',
    alignItems: 'center',
    width: '100%', // 横屏时宽度为100%
    height: '100%', // 横屏时高度为100%
  },
  video: {
    width: '100%',  // 让视频占据全屏宽度
    height: '100%', // 让视频占据全屏高度
  },
  xia: {
    position: 'absolute',
    bottom: 17,
    right: 120,
  },
  xia1: {
    position: 'absolute',
    bottom: 17,
    left: 160,
  },
  contentContainer: {
    flex: 1,
    padding: 10,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 50,
  },
  video: {
    width: 350,
    height: 275,
  },
  controlsContainer: {
    padding: 10,
  },
  playPauseButton: {
    color: 'red',
    fontSize: 18,
    marginTop: 20,
  },
  container: {
    flex: 1,
    backgroundColor: 'black',
    justifyContent: 'center',
    alignItems: 'center',
  },
  fullScreen: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    width: '100%',
    height: '100%',
  },
  video: {
    width: '100%',
    height: 300,
  },
  slider: {
    width: '0%',
    height: 40,
    marginTop: 20,
    display: 'none',
  },
  errorText: {
    color: 'red',
    textAlign: 'center',
    marginTop: 20,
  },
});

export default VideoPlayer;
